package com.jiaanpei.frameproject.modle.net;

import android.util.Log;

import com.jiaanpei.frameproject.BuildConfig;
import com.vise.log.ViseLog;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

public class LoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //Chain 里包含了request和response
        Request request = chain.request();
        long t1 = System.nanoTime();//请求发起的时间
        RequestBody requestBody = request.body();
        if(BuildConfig.isdev&&requestBody!=null){

            Headers headers = request.headers();

            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(Charset.forName("UTF-8"));
            }
            ViseLog.d("发出请求"+t1);
            ViseLog.json(buffer.readString(charset));
        }




        Response response = chain.proceed(request);
        long t2 = System.nanoTime();//收到响应的时间
        //不能直接使用response.body（）.string()的方式输出日志
        //因为response.body().string()之后，response中的流会被关闭，程序会报错，
        // 我们需要创建出一个新的response给应用层处理
        ResponseBody responseBody = response.peekBody(1024 * 1024);
        if(BuildConfig.isdev&&responseBody!=null){
            ViseLog.d("收到响应"+t2);
            ViseLog.json(responseBody.string());
        }

        return response;
    }
}
